'use client'

import { App } from "antd";
import { system } from "@/forent-api/api";
import useStore from "@/store/store";

//字段的类型
export interface SysDictProps {
    value: number;
    label: string;
}


export interface SysDictProps {
    value: number;
    label: string;
}

// 获取用户信息
export async function getUserInfo(): Promise<any>{
    const user = localStorage.getItem("sys_user");
    if(user){
        return JSON.parse(user);
    }
    return null;
}

//获取系统字典
export async function getSysDicts(type: string): Promise<SysDictProps[]> {
    const result = localStorage.getItem(type)
    if (result) {
        const parsedResult = JSON.parse(result);
        return parsedResult
    }
    return []
}


// 获取系统的字典数据
async function requestSysDict(type: string){
    const res = await system.getDictList({dict_type: type})
    if(res.code === 200){
        const data = res.data.data.map((item: any) => ({
            value: item.dict_id,
            label: item.dict_name
        }))
        localStorage.setItem(type, JSON.stringify(data))
    }
}

/**
 * @description: 初始化系统字典到Redux Store
 */
export const initSysDict = async () => {
  try {
    const res = await system.getDictList({ pageSize: 1000 }); // 获取所有字典
    if (res.code === 200 && res.data?.data) {
      const dicts = res.data.data;
      const dictMap = dicts.reduce((acc: any, dict: any) => {
        if (!acc[dict.dict_type]) {
          acc[dict.dict_type] = [];
        }
        acc[dict.dict_type].push({
          label: dict.dict_name,
          value: dict.dict_id,
        });
        return acc;
      }, {});
      useStore.dispatch({
        type: 'SET_SYS_DICTS',
        payload: { sysDicts: dictMap }
      });
    } else {
      console.error('系统字典初始化失败:', res.msg);
    }
  } catch (error) {
    console.error('系统字典初始化错误:', error);
  }
};

/**
 * @description: 初始化RBAC相关信息（占位）
 */
export const initRBAC = async () => {
    // 此函数可以用于初始化角色、权限等信息到Store
    // 目前在登录逻辑中直接调用，此处可作为预留
    console.log("RBAC inited");
};